package com.clive.llweb.exception;

import com.clive.llweb.vo.DishResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.transform.Result;
import java.util.List;
//加上这个注解就是全局异常处理类
@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {
//    捕获异常，凡是exception异常都来到这里处理
    @ExceptionHandler(value = Exception.class)
//  e 代表报错信息
    public DishResult exceptionHandler(Exception e){
        //      打印错误日志
        e.printStackTrace();
        if (e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
            //多个错误，取第一个
            FieldError error = fieldErrors.get(0);
            String msg = error.getDefaultMessage();
            return DishResult.error(msg);
        }
        return DishResult.error(e.getMessage());
    }
}